﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Microsoft.Dynamics.BusinessConnectorNet;

namespace PJ.Data
{
    public static class InvoicePostActivity
    {
        public static void PostInvoice(string customerId, string reference, string[] itemIds, double[] quantities, string[] units)
        {
            if (customerId == null || customerId == "")
                throw new ArgumentNullException("customerId");
            if (itemIds == null)
                throw new ArgumentNullException("itemIds");
            if (quantities == null)
                throw new ArgumentNullException("quantities");
            if (units == null)
                throw new ArgumentNullException("units");
            if (itemIds.Count() == 0)
                throw new ArgumentNullException("itemIds");
            if (quantities.Count() == 0)
                throw new ArgumentNullException("quantities");
            if (units.Count() == 0)
                throw new ArgumentNullException("units");
            if (quantities.Count() != itemIds.Count())
                throw new ArgumentException("Wrong number of items", "quantities");
            if (units.Count() != itemIds.Count())
                throw new ArgumentException("Wrong number of items", "units");

            if (reference == null)
                reference = "";
            using (AxaptaContainer itemIdContainer = DynamicsAX.DynamicsAXBroker.CreateContainer())
            {
                itemIdContainer.AddRange(itemIds);
                using (AxaptaContainer quantityContainer = DynamicsAX.DynamicsAXBroker.CreateContainer())
                {
                    quantityContainer.AddRange(quantities);
                    using (AxaptaContainer unitContainer = DynamicsAX.DynamicsAXBroker.CreateContainer())
                    {
                        unitContainer.AddRange(units);
                            // string test = (string)DynamicsAX.DynamicsAXBroker.StaticMethod("PJKSaleInvoiceAXProvider", "testTempName");
                            int[] pdfi = (int[])DynamicsAX.DynamicsAXBroker.StaticMethod("PJKSaleInvoiceAXProvider", "PostInvoice",
                                        new object[] { customerId, reference, itemIdContainer, quantityContainer, unitContainer });
                        byte[] pdf = new byte[pdfi.Length];
                        for (int i = 0; i < pdfi.Length; i++)
                            pdf[i] = (byte)pdfi[i];
                        Framework.PDFReader.PrintPdf(pdf);
                    }
                }
            }
        }

    }
}
